//文件系统

const { isUtf8 } = require("buffer");
const fs = require("fs");
const { buffer } = require("stream/consumers");

//整体读取文件内容
fs.readFile("04_sample.txt","utf-8",(err,data)=>{
    if(err){
        console.error(err);
    }else{
        console.log(data)
    }
});

//整体读取二进制文件内容
fs.readFile("04_nodejs.jpg",(err,data)=>{
    if(err){
        console.error(err);
    }else{
        console.log(data)
        console.log(data.length)
    }
});

//回调形式 并使用Buffer
fs.open("04_sample.txt","r",function(err,fd){
    if(err) throw err;
    console.log("打开文件...");
    let buffer = Buffer.alloc(1024);
    fs.read(fd,buffer,0,buffer.length,0,function(err,bytesRead,buffer){
        if(err) throw err;
        console.log(`读取字节${bytesRead}`);
        console.log(buffer.subarray(0,bytesRead).toString());
        fs.close(fd,err=>{
           if(err) throw err;
        });
    });
});

//Promise 形式使用
const fsPromises = fs.promises;
(async function(file){
    let filehadle;
    try{
       filehandle = await fsPromises.open(file);
       console.log(`已打开${file}文件`);
       let buffer = Buffer.alloc(1024);
       let res = await filehadle.read(buffer,0,buffer.length,0);
       console.log(`读取字节${res.bytesRead}\n`);
       console.log(`${res.buffer.toString()}`);
    }catch(error){
        console.error(error);
    }finally{
        if(filehadle){
            await filehandle.close();
        }
    }
})("04_sample.txt");

//写文件
let data = "hello,Node.js,欢迎使用"
fs.writeFile("04_output.txt",data,"utf-8",function(err){
      if(err){
        console.error(err);
      }else{
        console.log("写入完成.")
      }
});